package com.ofps.forms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ofps.forms.common.utils.R;
import com.ofps.forms.mapper.AnswerScoreMapper;
import com.ofps.forms.domain.AnswerScore;
import com.ofps.forms.domain.QuestionScore;
import com.ofps.forms.service.AnswerScoreService;
import com.ofps.forms.service.QuestionScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ofps.common.utils.SecurityUtils.getUserId;


@Service("answerScoreService")
public class AnswerScoreServiceImpl extends ServiceImpl<AnswerScoreMapper, AnswerScore> implements AnswerScoreService {

    @Resource
    private AnswerScoreMapper answerScoreMapper;

    @Autowired
    private QuestionScoreService questionScoreService;

    @Override
    public R save(HttpServletRequest request, AnswerScore answerScore) {
        //设置userId
//        answerScore.setUserId(TokenUtil.getId(request));
//        answerScore.setUserId(Math.toIntExact(getUserId()));

        //保存成功或失败
        return this.saveOrUpdate(answerScore) ? R.ok("保存填空题答案成功！") : R.error("保存填空题答案失败！");
    }

    @Override
    public R delete(Map<String, Object> body) {
        //根据id查询删除
        QueryWrapper<AnswerScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", body.get("id"));
        return answerScoreMapper.delete(queryWrapper) == 1 ? R.ok("删除成功！") : R.error("删除失败！");
    }

    @Override
    public List<AnswerScore> queryAnswerScoreWithQuestionId(Map<String, Object> body) {
        QueryWrapper<AnswerScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("question_id", body.get("question_id"));
        return answerScoreMapper.selectList(queryWrapper);
    }


    @Override
    public Map<String, Object> summerize(Map<String, Object> body) {
        List <AnswerScore> answerScoreEntityList = queryAnswerScoreWithQuestionId(body);
        List <QuestionScore> questionScoreEntityList = questionScoreService.queryQuestionScore(body);
        List<Object> TotalMessage = new ArrayList<>();
        for (AnswerScore answerScore : answerScoreEntityList){
            List<Object> message = new ArrayList<>();
            message.add(answerScore.getAnswer());
            TotalMessage.add(message);
        }
        Map<String,Object> summerizeMessage =new HashMap<>();
        summerizeMessage.put("totalMessage",TotalMessage);
        summerizeMessage.put("sum",answerScoreEntityList.size());
        summerizeMessage.put("type",6);
        return summerizeMessage;
//        return null;
    }
}
